package com.luoqiu.yygh.common.helper;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtHelper {

    private static final long expireTime = 24 * 60 * 60 * 1000;

    private static final String tokenSignKey = "luoqiu9464";

    public static String createToken(Long userId, String username) {
        return Jwts.builder().setSubject("YYGH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .claim("userId", userId)
                .claim("username", username)
                .signWith(SignatureAlgorithm.ES512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    public static Long getUserId(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        String userId = body.get("userId").toString();
        return Long.parseLong(userId);
    }


    public static String getUserName(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return body.get("username").toString();
    }
}
